package com.jack.leetcode.eachproblem_2020;

/**
 * Created by zhang_j on 2020/10/30
 */
public class 岛屿的周长 {

    public int islandPerimeter(int[][] grid) {
        int result = 0;
        int m = grid.length;
        int n = grid[0].length;
        for(int i = 0;i < m;i++){
            for(int j = 0;j < n;j++){
                if(grid[i][j] == 1){
                    result += count(i, j, grid);
                }
            }
        }
        return result;
    }
    int[][] dir = {{0, 1},{0, -1},{1, 0},{-1, 0}};
    private int count(int i, int j, int[][] grid){
        int result = 0;
        for (int[] ints : dir) {
            int newI = i + ints[0];
            int newJ = j + ints[1];
            boolean isValid = newI >= 0 && newI < grid.length
                    && newJ >= 0 && newJ < grid[0].length;
            if(isValid){
                result += grid[newI][newJ] == 1 ? 0 : 1;
            }else{
                result++;
            }
        }
        return result;
    }

}
